package com.zzh.oauth.intergration.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.List;

/**
 * http请求配置
 * @author zhangjinkun@xdf.cn
 * @date 2018/5/20
 */
@Configuration
public class RestTemplateConfig {
	@Bean
	public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
		RestTemplate restTemplate = new RestTemplate(factory);
		List<HttpMessageConverter<?>> converters = restTemplate.getMessageConverters();
		for (HttpMessageConverter<?> converter : converters) {
			if (converter instanceof MappingJackson2HttpMessageConverter) {
				MappingJackson2HttpMessageConverter jsonConverter = (MappingJackson2HttpMessageConverter) converter;
				jsonConverter.setObjectMapper(new ObjectMapper());
				jsonConverter.setSupportedMediaTypes(
						ImmutableList.of(
								new MediaType("application", "json", Charset.defaultCharset()),
								new MediaType("application", "x-www-form-urlencoded", Charset.defaultCharset()),
								new MediaType("text", "html", Charset.defaultCharset()),
								new MediaType("text", "plain", Charset.defaultCharset()),
								new MediaType("text", "javascript", Charset.defaultCharset())
						)
				);
			}
		}

		return restTemplate;
	}

	/**
	 * https请求配置
	 * @return
	 */
	@Bean
	public RestTemplate httpsRestTemplate(){
		return new RestTemplate(new HttpsClientRequestFactory());
	}

	@Bean
	public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
		SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
		//毫秒
		factory.setReadTimeout(60000);
		factory.setConnectTimeout(60000);
		return factory;
	}
}